package com.qk.management.web.Interceptor;

import com.qk.common.util.CurrentUserContextHolders;
import com.qk.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    private static final String LOGIN_HEADER_NAME = "token";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader(LOGIN_HEADER_NAME);
        Optional<String> optional = Optional.ofNullable(header);
        if(!optional.isPresent()){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        try {
            Claims claims = JwtUtil.parseToken(header);
            Integer id = claims.get("id", Integer.class);
            log.info("用户id为{}",id);
            CurrentUserContextHolders.set(id);
            String username = claims.get("username",String.class);
            log.info("用户名为{}",username);
            return true;
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserContextHolders.remove() ;
    };
}
